package com.kws.system.controller;

import java.util.List;

import cn.hutool.core.lang.tree.Tree;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kws.common.core.domain.R;
import com.kws.system.domain.info.QueryDictDataInfo;
import com.kws.system.domain.info.QueryMenuTreeInfo;
import com.kws.system.domain.vo.CreateMenuRq;
import com.kws.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.kws.common.core.constant.UserConstants;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.log.annotation.Log;
import com.kws.common.log.enums.BusinessType;
import com.kws.common.security.annotation.RequiresPermissions;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.system.domain.SysMenu;
import com.kws.system.service.ISysMenuService;

/**
 * 菜单信息
 * 
 * @author zhangyh
 */
@RestController
@RequestMapping("/menu")
@Api(tags = "菜单管理模块")
public class SysMenuController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 获取菜单列表
     */
//    @RequiresPermissions("system:menu:list")
    @GetMapping("/list")
    @ApiOperation("查询菜单列表")
    public R list(SysMenu menu)
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> sysMenus = menuService.selectMenuList(menu,userId);
        return R.ok(sysMenus);
    }

    @ApiOperation("分页查询菜单列表")
    @GetMapping("/query/menuPage")
    public R<List<SysMenu>> queryMenuPage(@RequestParam(required = false) String menuName){
        List<SysMenu> pageInfo = menuService.queryMenuPage(menuName);
        return R.ok(pageInfo);
    }

    @ApiOperation("查询各系统模块菜单树")
    @GetMapping("/query/menuTree")
    public R<QueryMenuTreeInfo> queryMenuTree(@RequestParam Long roleId){
        QueryMenuTreeInfo info = menuService.queryMenuTree(roleId);
        return R.ok(info);
    }

    /**
     * 根据菜单编号获取详细信息
     */
//    @RequiresPermissions("system:menu:query")
    @ApiOperation("根据菜单ID查询菜单详情")
    @GetMapping(value = "/{menuId}")
    public R getInfo(@PathVariable Long menuId)
    {
        return R.ok(menuService.selectMenuById(menuId));
    }

//    /**
//     * 获取菜单下拉树列表
//     */
//    @GetMapping("/treeselect")
//    @ApiOperation("获取菜单权限树")
//    public R treeselect(SysMenu menu)
//    {
//        Long userId = SecurityUtils.getUserId();
//        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
//        return R.ok(menuService.buildMenuTreeSelect(menus));
//    }

//    /**
//     * 加载对应角色菜单列表树
//     */
//    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
//    @ApiOperation("根据角色ID查询对应菜单权限树")
//    public R roleMenuTreeselect(@PathVariable("roleId") Long roleId)
//    {
//        Long userId = SecurityUtils.getUserId();
//        List<SysMenu> menus = menuService.selectMenuList(userId);
//        JSONObject resultJson = new JSONObject();
//        resultJson.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
//        resultJson.put("menus", menuService.buildMenuTreeSelect(menus));
//        return R.ok(resultJson);
//    }

    /**
     * 新增菜单
     */
//    @RequiresPermissions("system:menu:add")
    @ApiOperation("新增菜单数据")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody CreateMenuRq rq)
    {
//        if (!menuService.checkMenuNameUnique(menu))
//        {
//            return R.fail("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
//        }
//        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
//        {
//            return R.fail("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
//        }
//        menu.setCreateBy(SecurityUtils.getUsername());
        return menuService.createMenu(rq);
    }

    /**
     * 修改菜单
     */
//    @RequiresPermissions("system:menu:edit")
    @ApiOperation("修改菜单权限")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysMenu menu)
    {
        if (!menuService.checkMenuNameUnique(menu))
        {
            return R.fail("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
//        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
//        {
//            return R.fail("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
//        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            return R.fail("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
//    @RequiresPermissions("system:menu:remove")
    @ApiOperation("根据菜单ID删除菜单权限")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public R remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            return R.fail("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId))
        {
            return R.fail("菜单已分配,不允许删除");
        }
        return R.ok(menuService.deleteMenuById(menuId));
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    @ApiOperation("获取菜单权限路由")
    public R getRouters()
    {
        QueryDictDataInfo dataInfo = dictDataService.selectDictDataById(11111111111L);
        if(dataInfo == null || !StringUtils.equals("1",dataInfo.getDictValue())){
            return R.fail("使用权限已过期，请联系管理员续期");
        }
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return R.ok(menuService.buildMenus(menus));
    }
}